package ntd.remote.online;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import ntd.remote.online.bo.OnlineInfo;
import ntd.tool.abnormal.ComAbnormal;
import ntd.util.UtilName;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ComOnline {

    private static final Map<String, Map<String, OnlineInfo>> onlineMapInfo = new HashMap<>();

    /**
     * 在线注册
     * @param onlineInfo
     * @param type
     */
    public static void online(String type, OnlineInfo onlineInfo) {
        initOnlineInfo(onlineInfo);
        getOnlineInfoMap(type).put(onlineInfo.getClientCode(), onlineInfo);
    }

    /**
     * 离线注销
     * @param type
     * @param code
     */
    public static void offLine(String type, String code) {
        getOnlineInfoMap(type).remove(code);
    }

    public static void online(OnlineInfo onlineInfo) {
        online("user", onlineInfo);
    }

    public static OnlineInfo getOnlineInfo(String type, String code) {
        return getOnlineInfoMap(type).get(code);
    }

    public static List<OnlineInfo> ListOnlineInfo() {
        return ListOnlineInfo("user");
    }

    /**
     * 根据类型获取在线数据列表
     * @param type
     * @return
     */
    public static List<OnlineInfo> ListOnlineInfo(String type) {
        return ListUtil.toList(getOnlineInfoMap(type).values());
    }

    /**
     * 获取对应类型在线列表
     * @param type
     * @return
     */
    private static Map<String, OnlineInfo> getOnlineInfoMap(String type) {
        Map<String, OnlineInfo> onlineInfoMap = onlineMapInfo.get(type);
        if (ObjectUtil.isNull(onlineInfoMap)) {
            onlineInfoMap = new HashMap<>();
            onlineMapInfo.put(type, onlineInfoMap);
        }
        return onlineInfoMap;
    }

    /**
     * 初始化在线信息
     * @param onlineInfo
     */
    private static void initOnlineInfo(OnlineInfo onlineInfo) {
        Opt.ofBlankAble(onlineInfo.getClientCode()).orElseThrow(() -> new ComAbnormal("clientCode 不能为空！"));
        onlineInfo.setCreateTime(LocalDateTime.now());
        onlineInfo.setName(ObjectUtil.defaultIfBlank(onlineInfo.getName(), UtilName.getName()));
        onlineInfo.setParentName(ObjectUtil.defaultIfBlank(onlineInfo.getParentName(), "逆态度"));
    }

}
